/*
 * Project Name spring-boot-tools
 * File Name TenantInterceptor
 * Package Name com.huxiaosu.tools.mybatis.extend
 * Create Time 2024/7/15
 * Create by name：liujie
 */
package com.huxiaosu.tools.mybatis.extend.tenant;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.huxiaosu.tools.common.base.LogonUser;
import com.huxiaosu.tools.common.holder.LogonUserHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

import java.util.List;

/**
 * Description
 *
 * @author liujie
 * @date 2024/7/15 16:35
 */
public class TenantInterceptor extends TenantLineInnerInterceptor {
    public TenantInterceptor(TenantProperties tenantProperties) {
        super(new TenantLineHandler() {
            // 获取租户id ,若没有则传入 -1
            @Override
            public Expression getTenantId() {
                LogonUser logonUser = LogonUserHolder.get();
                String tenantId = tenantProperties.getDefaultTenantId();
                if (logonUser != null) {
                    tenantId = logonUser.getTenantId();
                }
                return new LongValue(tenantId);
            }

            // 忽略表,true 表示忽略该表
            @Override
            public boolean ignoreTable(String tableName) {
                LogonUser logonUser = LogonUserHolder.get();
                if (logonUser == null) {
                    return true;
                }
                // 指定账户不受影响
                List<String> adminAccount = tenantProperties.getAdminAccount();
                String logonUsername = logonUser.getUsername();
                if(adminAccount.stream().anyMatch(e -> e.equals(logonUsername))){
                    return true;
                }
                // 如果没有配置 ignore 则返回false表示需要追加租户条件
                List<String> ignoreTables = tenantProperties.getIgnoreTables();
                if (CollUtil.isEmpty(ignoreTables) || ignoreTables.isEmpty()) {
                    return false;
                }
                return ignoreTables.stream().anyMatch(e -> e.equalsIgnoreCase(tableName));
            }

            // 多租户的列名自定义
            @Override
            public String getTenantIdColumn() {
                return tenantProperties.getTableField();
            }
        });
    }
}